package com.gxa.utils;

import java.util.Calendar;
import java.util.Date;

/**
 * 通过员工入职时间计算员工工龄
 */
public class WorkAge {

    /**
     * 通过员工入职时间计算员工工龄
     *
     * @param entryDate     员工入职时间
     * @return              返回一个int型的员工工龄
     */
    public static int getWorkAge(Date entryDate){
        Calendar calendar = Calendar.getInstance();
        int yearNow = calendar.get(Calendar.YEAR);               //当前年份
        int monthNow = calendar.get(Calendar.MONTH);             //当前月份
        int dayOfMonthNow = calendar.get(Calendar.DAY_OF_MONTH); //当前日期
        calendar.setTime(entryDate);
        int workYear = calendar.get(Calendar.YEAR);
        int workMonth = calendar.get(Calendar.MONTH);
        int workDay = calendar.get(Calendar.DAY_OF_MONTH);

        //得到工龄
        int gonglin = yearNow - workYear; //得到年差
        //若目前月数少于开始工作时间的月数，年差-1
        if (monthNow < workMonth){
            gonglin--;
        }else if (monthNow == workMonth){
            //当月数相等时，判断日数，若当月的日数小于开始工作时间的日数，年差-1
            if (dayOfMonthNow < workDay){
                gonglin--;
            }
        }
        return gonglin;
    }
}
